<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Table } from '@/components/Table'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  sysDictTypeListApi,
  sysDictDataListApi,
  sysDictRelsListApi,
  sysDictRelsAddApi,
  sysDictRelsEditApi,
  sysDictRelsDelApi
} from '@/api/dict'
import { dictRels } from '@/api/dict/types'
import { useTable } from '@/hooks/web/useTableTest'

const { register, tableObject, methods } = useTable<
  {
    count: number
    data: dictRels[]
  },
  dictRels
>({
  getListApi: sysDictRelsListApi,
  response: {
    count: 'count',
    data: 'data'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const dictTypeData = ref<any>([])
const pDictDataList = ref<any>([])
const cDictDataList = ref<any>([])
const pDictDataListForm = ref<any>([])
const cDictDataListForm = ref<any>([])

const dictType = async () => {
  const res = await sysDictTypeListApi({})
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictTypeData.value = res.data
  }
}
dictType()
const searchRef = ref<ComponentRef<typeof Search>>()
const onPType = async (dict_type) => {
  if (dict_type) {
    const res = await sysDictDataListApi({ dict_type })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      pDictDataList.value = res.data
      const search = unref(searchRef)
      search?.nullField('p_value')
    }
  } else {
    pDictDataList.value = []
    const search = unref(searchRef)
    search?.nullField('p_value')
  }
}
const onCType = async (dict_type) => {
  if (dict_type) {
    const res = await sysDictDataListApi({ dict_type })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      cDictDataList.value = res.data
      const search = unref(searchRef)
      search?.nullField('c_value')
    }
  } else {
    cDictDataList.value = []
    const search = unref(searchRef)
    search?.nullField('c_value')
  }
}
const onPTypeForm = async (dict_type, isNull = true) => {
  if (dict_type) {
    const res = await sysDictDataListApi({ dict_type })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      pDictDataListForm.value = res.data
      if (isNull) {
        const edit = unref(editRef)
        let model: any = await edit?.getFormData()
        model['p_value'] = ''
      }
    }
  } else {
    pDictDataListForm.value = []
    if (isNull) {
      const edit = unref(editRef)
      let model: any = await edit?.getFormData()
      model['p_value'] = ''
    }
  }
}
const onCTypeForm = async (dict_type, isNull = true) => {
  if (dict_type) {
    const res = await sysDictDataListApi({ dict_type })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      cDictDataListForm.value = res.data
      if (isNull) {
        const edit = unref(editRef)
        let model: any = await edit?.getFormData()
        model['c_value'] = ''
      }
    }
  } else {
    cDictDataListForm.value = []
    if (isNull) {
      const edit = unref(editRef)
      let model: any = await edit?.getFormData()
      model['c_value'] = ''
    }
  }
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'dict_rels_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    form: {
      show: false
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'p_type',
    label: '父级字典类型',
    search: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'name',
          valueField: 'code'
          // labelField: 'label',
          // valueField: 'value'
        },
        options: dictTypeData,
        onChange: onPType
      },
      show: true
    },
    form: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'name',
          valueField: 'code'
          // labelField: 'label',
          // valueField: 'value'
        },
        options: dictTypeData,
        onChange: onPTypeForm
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'p_type_name',
    label: '父级字典类型',
    form: {
      show: false
    }
  },
  {
    field: 'p_value',
    label: '父级字典键值',
    search: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'label',
          valueField: 'value'
        },
        options: pDictDataList
      },
      show: true
    },
    form: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'label',
          valueField: 'value'
        },
        options: pDictDataListForm
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'p_value_label',
    label: '父级字典键值',
    form: {
      show: false
    }
  },
  {
    field: 'c_type',
    label: '子级字典类型',
    search: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'name',
          valueField: 'code'
        },
        options: dictTypeData,
        onChange: onCType
      },
      show: true
    },
    form: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'name',
          valueField: 'code'
        },
        options: dictTypeData,
        onChange: onCTypeForm
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'c_type_name',
    label: '子级字典类型',
    form: {
      show: false
    }
  },
  {
    field: 'c_value',
    label: '子级字典键值',
    search: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'label',
          valueField: 'value'
        },
        options: cDictDataList
      },
      show: true
    },
    form: {
      component: 'Select',
      componentProps: {
        optionsAlias: {
          labelField: 'label',
          valueField: 'value'
        },
        options: cDictDataListForm
      },
      show: true
    },
    table: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'c_value_label',
    label: '子级字典键值',
    form: {
      show: false
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 260,
    label: t('tableDemo.action'),
    fixed: 'right',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = (type: string, row: dictRels) => {
  actionType.value = type
  switch (type) {
    case 'add':
      dialogTitle.value = t('新增')
      tableObject.currentRow = {}
      dialogVisible.value = true
      pDictDataListForm.value = []
      cDictDataListForm.value = []
      break
    case 'edit':
      dialogTitle.value = t('编辑')
      tableObject.currentRow = row
      dialogVisible.value = true
      onPTypeForm(row.p_type, false)
      onCTypeForm(row.c_type, false)
      break
    case 'see':
      dialogTitle.value = t('详情')
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.dict_rels_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      break
  }
}

const apiDel = async (dict_rels_id) => {
  let delRes = await sysDictRelsDelApi({ dict_rels_id: dict_rels_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async () => {
  if (actionType.value == 'add') {
    const edit = unref(editRef)
    await edit?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await edit?.getFormData()) as dictRels
        const res = await sysDictRelsAddApi(data)
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  } else {
    const edit = unref(editRef)
    await edit?.elFormRef?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        const data = (await edit?.getFormData()) as dictRels
        const res = await sysDictRelsEditApi(data)
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }
    })
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add', {})">{{ t('exampleDemo.add') }}</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action('edit', row)">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="success" @click="action('see', row)">
          {{ t('exampleDemo.detail') }}
        </ElButton>
        <ElButton type="danger" @click="action('del', row)">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'add'"
        type="primary"
        :loading="loading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
